package com.opentool.web.service.impl;
import com.opentool.util.IpUtil;
import com.opentool.web.db.RowMapper;
import com.opentool.web.db.SqlliteConnection;
import com.opentool.web.module.LocalDnsRecord;
import com.opentool.web.service.ILocalDnsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Service
@Slf4j
public class LocalDnsServiceImpl implements ILocalDnsService {

    @Resource(name = "sqlliteConnection")
    private SqlliteConnection sqlliteConnection;

    @Override
    public byte[] dnsResolver(String domain, String sourceIp) {
        try{
            domain=domain.substring(0,domain.lastIndexOf("."));
            String sql="Select target_ip From t_localdns Where domain_name='"+domain+"' And source_ip='"+sourceIp+"'";
            if(StringUtils.isNotEmpty(sourceIp)){
                sql+=" And source_ip='"+sourceIp+"' ";
            }
            List<String> rows = sqlliteConnection.executeQuery(sql, new RowMapper<String>() {
                public String mapRow(ResultSet rs, int index) throws SQLException {
                    return rs.getString("target_ip");
                }
            });
            if(CollectionUtils.isNotEmpty(rows)){
                String targetIp=rows.get(0);
                byte[] bytes=IpUtil.ipToHex(targetIp);
                return bytes;
            }else{
                sql="Select target_ip From t_localdns Where domain_name='"+domain+"' ";
                rows = sqlliteConnection.executeQuery(sql, new RowMapper<String>() {
                    public String mapRow(ResultSet rs, int index) throws SQLException {
                        return rs.getString("target_ip");
                    }
                });
                if(CollectionUtils.isNotEmpty(rows)){
                    String targetIp=rows.get(0);
                    byte[] bytes=IpUtil.ipToHex(targetIp);
                    return bytes;
                }
            }
        }catch (Exception e){
            log.error("DNS解析错误[{},{}]",domain,sourceIp,e);
        }
        return new byte[]{0,0,0,0};
    }

    @Override
    public String queryDnsServer() {
        try{
            String sql="Select dns_server From t_sysconfig ";
            List<String> rows = sqlliteConnection.executeQuery(sql, new RowMapper<String>() {
                public String mapRow(ResultSet rs, int index) throws SQLException {
                    return rs.getString("dns_server");
                }
            });
            if(CollectionUtils.isNotEmpty(rows)){
                return rows.get(0);
            }
        }catch (Exception e){
            log.error("查询系统配置远端DNS服务失败",e);
        }
        return "223.5.5.5";
    }

    @Override
    public void saveDnsServer(String ipAddr) {
        try{
            sqlliteConnection.execute("Delete From t_sysconfig");
            sqlliteConnection.execute("Insert Into t_sysconfig (dns_server) Values ('"+ipAddr+"')");
        }catch (Exception e){
            log.error("保存系统配置远端DNS服务失败",e);
        }
    }

    @Override
    public void saveLocalDnsRecord(LocalDnsRecord localDnsRecord) {
        try{
            sqlliteConnection.execute("Insert Into t_localdns (id,domain_name,source_ip,target_ip) Values ((SELECT last_insert_rowid())+1,'"+localDnsRecord.getDomainName()+"','"+localDnsRecord.getSourceIp()+"','"+localDnsRecord.getTargetIp()+"')");
        }catch (Exception e){
            log.error("保存本地DNS解析记录错误",e);
        }
    }

    @Override
    public List<LocalDnsRecord> queryLocalDnsRecord() {
        try{
            String sql="Select * From t_localdns ";
            List<LocalDnsRecord> rows = sqlliteConnection.executeQuery(sql, new RowMapper<LocalDnsRecord>() {
                public LocalDnsRecord mapRow(ResultSet rs, int index) throws SQLException {
                    LocalDnsRecord localDnsRecord=new LocalDnsRecord();
                    localDnsRecord.setId(rs.getInt("id"));
                    localDnsRecord.setDomainName(rs.getString("domain_name"));
                    localDnsRecord.setSourceIp(rs.getString("source_ip"));
                    localDnsRecord.setTargetIp(rs.getString("target_ip"));
                    return localDnsRecord;
                }
            });
           return rows;
        }catch (Exception e){
            log.error("查询系统配置远端DNS服务失败",e);
        }
        return null;
    }

    @Override
    public void deleteLocalDnsRecord(Integer id) {
        try{
            sqlliteConnection.execute("Delete From  t_localdns Where id="+id+"");
        }catch (Exception e){
            log.error("删除本地DNS解析记录错误",e);
        }
    }
}
